package com.sinosoft.framework.mvc;

import com.sinosoft.framework.annotation.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.net.URL;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @author ZZZ
 * @version 1.0
 * @desc 模拟springMVC自定义DispatherServlet
 * @date 2018/6/11 0011
 */
public class DispatherServlet extends HttpServlet {

    //配置文件
    Properties properties = new Properties();
    //要扫描的包路径
    List<String> classNames = new ArrayList<>();
    //IOC容器
    Map<String, Object> IOC = new HashMap<>();
    //请求映射
    List<HandlerAdapter> handlerMapping = new ArrayList<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            doDispath(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 请求转发
     */
    private void doDispath(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String requestURI = req.getRequestURI();
        String contextPath = req.getContextPath();

        requestURI = requestURI.replace(contextPath, "").replaceAll("/+", "/");
        if (requestURI == null || "/".equals(requestURI)) {
            return;
        }

        for (HandlerAdapter handlerAdapter : handlerMapping) {
            if (handlerAdapter.pattern.matcher(requestURI).find()) {
                Map<String, Integer> params = handlerAdapter.paramIndexMapping;
                String[] paramArray = new String[params.size()];
                for (Map.Entry<String, Integer> entry : params.entrySet()) {
                    paramArray[entry.getValue()] = entry.getKey();
                }
                Object result = handlerAdapter.invokeMethod(req, resp);
                resp.getWriter().write(result.toString());
                return;
            }
        }

        try {
            resp.getWriter().write("404 Not Found!");
            return;
        } catch (IOException e) {
            e.printStackTrace();
            resp.getWriter().write("500 Internal Exception!");
        }
    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        //1.读取配置文件
        doLoadConfig(servletConfig.getInitParameter("contextConfigLocation"));
        //2.扫描待扫描的包
        doScanner(properties.getProperty("packageScan"));
        //3.初始化所有Bean
        doInitializeBean();
        //4.依赖注入
        doInjection();
        //5.请求映射
        doHandlerMapping();
    }

    /**
     * @desc 扫描所有待扫描的包
     * @author ZZZ
     * @date 2018/6/11 0011
     * @version 1.0
     */
    private void doScanner(String strPackageScan) {
        URL url = this.getClass().getResource("/" + strPackageScan.replaceAll("\\.", "//"));
        File file = new File(url.getFile());
        for (File f : file.listFiles()) {
            if (f.isDirectory()) {
                doScanner(strPackageScan + "." + f.getName());
            } else {
                String className = strPackageScan + "." + f.getName().replaceAll(".class", "");
                classNames.add(className);
            }
        }
    }

    /**
     * @desc 请求映射
     * @author ZZZ
     * @date 2018/6/11 0011
     * @version 1.0
     */
    private void doHandlerMapping() {
        if (IOC.isEmpty()) {
            return;
        }
        for (Map.Entry<String, Object> entry : IOC.entrySet()) {
            String baseUrl = "";
            Class<?> clazz = entry.getValue().getClass();
            if (!clazz.isAnnotationPresent(Controller.class)) {
                continue;
            }
            //如果controler上写了@RequestMapping
            if (clazz.isAnnotationPresent(RequestMapping.class)) {
                RequestMapping requestMapping = clazz.getAnnotation(RequestMapping.class);
                baseUrl = requestMapping.value();
            }
            //遍历所有公共的方法
            for (Method method : clazz.getMethods()) {
                if (!method.isAnnotationPresent(RequestMapping.class)) {
                    continue;
                }
                RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
                String regex = baseUrl + "/" + requestMapping.value();
                regex = regex.replaceAll("/+", "/");
                Pattern pattern = Pattern.compile(regex);
                handlerMapping.add(new HandlerAdapter(entry.getValue(), method, pattern));
                System.out.println("RequestMapping: " + regex + "," + method);
            }
        }
    }

    /**
     * @desc 依赖注入
     * @author ZZZ
     * @date 2018/6/11 0011
     * @version 1.0
     */
    private void doInjection() {
        if (IOC.isEmpty()) {
            return;
        }
        for (Map.Entry<String, Object> entry : IOC.entrySet()) {
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            for (Field field : fields) {
                if (!field.isAnnotationPresent(Autowired.class)) {
                    continue;
                }
                //更改访问权限
                field.setAccessible(true);
                try {
                    String beanName = lowerFirstCase(field.getType().getSimpleName());
                    //调用反射，给对象的属性赋值
                    field.set(entry.getValue(), IOC.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    continue;
                }
            }
        }
    }

    /**
     * @desc 初始化所有Bean
     * @author ZZZ
     * @date 2018/6/11 0011
     * @version 1.0
     */
    private void doInitializeBean() {
        if (classNames.isEmpty()) return;
        for (String str : classNames) {
            try {
                Class<?> clazz = Class.forName(str);
                //默认类名首字母小写
                String beanName = lowerFirstCase(clazz.getSimpleName());
                if (clazz.isAnnotationPresent(Controller.class)) {
                    Controller controller = clazz.getAnnotation(Controller.class);
                    if (!"".equals(controller.value())) {
                        beanName = controller.value();
                    }
                    IOC.put(beanName, clazz.newInstance());
                } else if (clazz.isAnnotationPresent(Service.class)) {
                    Service service = clazz.getAnnotation(Service.class);
                    if (!"".equals(service.value())) {
                        beanName = service.value();
                    }
                    IOC.put(beanName, clazz.newInstance());
                    /**
                     * 接口实现类的实例，名称为接口名称首字母小写
                     */
                    for (Class<?> i : clazz.getInterfaces()) {
                        IOC.put(lowerFirstCase(i.getSimpleName()), clazz.newInstance());
                    }
                } else {
                    continue;
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @desc 读取配置文件
     * @author ZZZ
     * @date 2018/6/11 0011
     * @version 1.0
     */
    private void doLoadConfig(String contextConfigLocation) {
        try (InputStream is = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation)) {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @desc 首字母小写
     * @author ZZZ
     * @date 2018/6/11 0011
     * @version 1.0
     */
    private String lowerFirstCase(String str) {
        return str.substring(0, 1).toLowerCase() + str.substring(1);
    }

    class HandlerAdapter {
        private Object handler;
        private Method method;
        private Pattern pattern;
        private Map<String, Integer> paramIndexMapping;
        private Object[] args;

        public HandlerAdapter(Object handler, Method method, Pattern pattern) {
            this.handler = handler;
            this.method = method;
            this.pattern = pattern;

            paramIndexMapping = new HashMap<String, Integer>();
            paramIndexMapping(method);
        }

        private void paramIndexMapping(Method method) {
            Annotation[][] annotations = method.getParameterAnnotations();
            for (int i = 0; i < annotations.length; i++) {
                for (Annotation annotation : annotations[i]) {
                    if (annotation instanceof RequestParam) {
                        String paramName = ((RequestParam) annotation).value();
                        boolean required = ((RequestParam) annotation).required();
                        if (!"".equals(paramName.trim())) {
                            paramIndexMapping.put(paramName, i);
                        }
                    }
                }
            }

            Class<?>[] paramTypes = method.getParameterTypes();
            for (int i = 0; i < paramTypes.length; i++) {
                Class<?> type = paramTypes[i];
                if (type == HttpServletRequest.class || type == HttpServletResponse.class) {
                    paramIndexMapping.put(type.getName(), i);
                }
            }
        }

        private Object invokeMethod(HttpServletRequest req,HttpServletResponse resp) throws Exception{
            int paramCount = method.getParameterCount();
            args = new Object[paramCount];

            Parameter[] parameters = method.getParameters();
            for(int i = 0; i < paramCount; i++){
                String paramName = parameters[i].getName();
                Class<?> paramType = parameters[i].getType();

                Annotation[] annotations = parameters[i].getAnnotations();
                if(annotations.length > 1){
                    throw new Exception("One parameter cant's has more the one annotation!");
                }
                for(Annotation annotation: annotations){
                    if (annotation instanceof RequestParam) {
                        paramName = ((RequestParam) annotation).value();
                    }
                }

                Object paramValue = null;
                if(paramType == HttpServletRequest.class){
                    paramValue = req;
                }else if(paramType == HttpServletResponse.class){
                    paramValue = resp;
                }
                if (paramValue == null) {
                    String[] paramValues = req.getParameterValues(paramName);
                    if (paramValues != null) {
                        paramValue = (paramValues.length == 1 ? paramValues[0] : paramValues);
                    }
                }
                args[i] = paramValue;
            }
            return method.invoke(handler,args);
        }
    }
}
